package com.android.bookgarden.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.bookgarden.MainActivity;
import com.android.bookgarden.MyApplication;
import com.android.bookgarden.R;
import com.android.bookgarden.apis.Apis;
import com.android.bookgarden.base.BaseActivity;
import com.android.bookgarden.bean.DataBean;
import com.android.bookgarden.bean.UserInfo;
import com.android.bookgarden.constract.RealtConstract;
import com.android.bookgarden.network.HttpType;
import com.android.bookgarden.persenter.BasePersenter;
import com.android.bookgarden.utli.FileFactory;
import com.android.bookgarden.utli.GetPathFromUri;
import com.android.bookgarden.utli.ImageUtlis;
import com.android.bookgarden.utli.IntentUtil;
import com.android.bookgarden.utli.JsonUitl;
import com.android.bookgarden.utli.LogUtil;
import com.android.bookgarden.utli.SpUtils;
import com.android.bookgarden.utli.UriUtil;
import com.android.bookgarden.utli.Utlis;
import com.android.bookgarden.views.CircleImageView;
import com.android.bookgarden.views.LoadingDialog;
import com.android.bookgarden.views.SelectPicDialog;
import com.bumptech.glide.Glide;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.feezu.liuli.timeselector.TimeSelector;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * Create by zouqh
 * on 2018/11/29
 **/
public class PersonInfoActivity extends BaseActivity implements View.OnClickListener, SelectPicDialog.DialogCallBack,RealtConstract.View {
    @BindView(R.id.close)
    ImageView close;
    @BindView(R.id.title_text)
    TextView titleText;
    @BindView(R.id.ritgh_icon)
    ImageView ritghIcon;
    @BindView(R.id.ritgh_text)
    TextView ritghText;
    @BindView(R.id.headImg)
    CircleImageView headImg;
    @BindView(R.id.nickname)
    TextView nickname;
    @BindView(R.id.nicknameLayout)
    RelativeLayout nicknameLayout;
    @BindView(R.id.sex)
    TextView sex;
    @BindView(R.id.sexLayout)
    RelativeLayout sexLayout;
    @BindView(R.id.birthday)
    TextView birthday;
    @BindView(R.id.birthdayLayout)
    RelativeLayout birthdayLayout;
    @BindView(R.id.city)
    TextView city;
    @BindView(R.id.cityLayout)
    RelativeLayout cityLayout;
    @BindView(R.id.changeLoginPass)
    RelativeLayout changeLoginPass;
    @BindView(R.id.payPassLayout)
    RelativeLayout payPassLayout;

    @BindView(R.id.exit)
    TextView exit;

    private TimeSelector timeSelector;
    private SelectPicDialog selectPicDialog;
    private SelectPicDialog selectSexDialog;

    private File avatarFile;
    private Uri avatarUri;
    private static final int REQUEST_PICK_PICTURE = 10002;
    private static final int REQUEST_TAKE_PHOTO = 10003;
    private static final int REQUEST_CROP_IMAGE = 10004;
    private RealtConstract.Presenter presenter;
    public static PersonInfoActivity personInfoActivity ;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_change_info;
    }

    @Override
    protected void initView() {
        personInfoActivity = this;
        presenter = new BasePersenter(this,this);
        titleText.setText("修改个人资料");
        close.setOnClickListener(this);
        cityLayout.setOnClickListener(this);
        changeLoginPass.setOnClickListener(this);
        birthdayLayout.setOnClickListener(this);
        headImg.setOnClickListener(this );
        nicknameLayout.setOnClickListener(this);
        payPassLayout.setOnClickListener(this);
        sexLayout.setOnClickListener(this);
        exit.setOnClickListener(this);
        timeSelector = new TimeSelector(this, new TimeSelector.ResultHandler() {
            @Override
            public void handle(String time) {
                birthday.setText(time.substring(0,10));
//                Toast.makeText(getApplicationContext(), time, Toast.LENGTH_LONG).show();
                Map<String,String> map = new HashMap<>();

                    map.put("birthday",time.substring(0,10));

                LoadingDialog.showMassge(PersonInfoActivity.this,"修改中...");
                presenter.loadDataGetHeader(map,"",Apis.CHANGE_BIRTH,1003,Utlis.getHeadler(PersonInfoActivity.this));

            }
        }, "1766-10-30 11:00", new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()));
        timeSelector.setMode(TimeSelector.MODE.YMD);//只显示 年月日
        LoadingDialog.showMassge(this,"获取信息...");
        presenter.loadDataHeader(null,"", Apis.GET_USERINFO,1001, Utlis.getHeadler(PersonInfoActivity.this), HttpType.GET);

    }

    @Override
    public void onRequestPermissions(String str, boolean z) {
        if (z){
            setSelImg();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        setInfo();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.close:
                finish();
                break;
            case R.id.changeLoginPass:
                startActivity(ChangePassActivity.class);
                break;
            case R.id.cityLayout:
                startActivity(InputCityActivity.class);
                break;

            case R.id.birthdayLayout:
                timeSelector.show();
                break;
            case R.id.headImg:
                checkSelfPermissions("1",new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE});

                break;
            case R.id.nicknameLayout:
                startActivity(EditNicknameUI.class);
                break;
            case R.id.payPassLayout:
                startActivity(SettingPayPassActivity.class);
                break;
            case R.id.sexLayout:
                setSex();
                break;

            case R.id.exit:
                MyApplication.getInstance().userInfo = null;
                SpUtils.getInstance().save(PersonInfoActivity.this,"token","");
                MainActivity.mainActivity.token = "";
                finish();

                break;
        }
    }

    private void setSelImg() {
        View view = LayoutInflater.from(this).inflate(R.layout.send_circle_select, null);
        if (selectPicDialog == null) {
            selectPicDialog = new SelectPicDialog(this, R.style.CustomDialog, view, new SelectPicDialog.DialogCallBack() {
                @Override
                public void selectPic(int position) {
                    if (position==1){
                        Intent pickingPictureIntent = IntentUtil.getIntentOfPickingPicture();
                        if (pickingPictureIntent.resolveActivity(getPackageManager()) != null) {
                            startActivityForResult(pickingPictureIntent, REQUEST_PICK_PICTURE);
                        }
                    }else{
                        if (UriUtil.checkPermissionGranted(PersonInfoActivity.this, Manifest.permission.CAMERA)) {//如果已经授予相机相关权限
                            openCamera();
                        } else {//如果相机权限并未被授予, 主动向用户请求该权限
                            if (UriUtil.requireSDKInt(Build.VERSION_CODES.M)) {//Android 6.0+时, 动态申请权限
                                requestPermissions(new String[]{Manifest.permission.CAMERA}, 10001);
                            } else {
                                Toast.makeText(PersonInfoActivity.this, "请开启相机权限", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                    selectPicDialog.dismiss();
                }
            });
        }
        selectPicDialog.show();
    }

    private void setSex(){
        if (selectSexDialog == null) {
            View view = LayoutInflater.from(this).inflate(R.layout.select_sex_dialog, null);
            selectSexDialog = new SelectPicDialog(this, R.style.CustomDialog, view, new SelectPicDialog.DialogCallBack() {
                @Override
                public void selectPic(int position) {
                    if (position==1){
                        sex.setText("男");
                    }else{
                        sex.setText("女");
                    }
                    selectSexDialog.dismiss();
                    String bss = "";
                    Map<String,String> map = new HashMap<>();
                    if (sex.getText().toString().equals("男")){
                        map.put("gender","1");
                        bss="1";
                    }else{
                        bss="0";
                        map.put("gender","0");
                    }
                   LoadingDialog.showMassge(PersonInfoActivity.this,"修改中...");
                    presenter.loadDataGetHeader(map,"",Apis.CHANGE_SEX,1002,Utlis.getHeadler(PersonInfoActivity.this));
                    // TODO 网络请求
                }
            });
        }
        selectSexDialog.show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 10001:
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openCamera();
                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(PersonInfoActivity.this, "相机权限已被拒绝", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    private void cropImage(Uri uri) {
        Intent croppingImageIntent = IntentUtil.getIntentOfCroppingImage(this, uri);
        if (croppingImageIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(croppingImageIntent, REQUEST_CROP_IMAGE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_TAKE_PHOTO) {
                avatarUri = UriUtil.getUriFromFileProvider(avatarFile);
                cropImage(avatarUri);
            } else if (requestCode == REQUEST_PICK_PICTURE) {
                if (data != null && data.getData() != null) {
//                    avatarFile = FileFactory.createTempImageFile(this);
                    /*
                     * Uri(data.getData()) from Intent(data) is not provided by our own FileProvider,
                     * so we can't grant it the permission of read and write programmatically
                     * through {@link IntentUtil#grantIntentAccessUriPermission(Context, Intent, Uri)},
                     * So we have to copy to our own Uri with permission of write and read granted
                     */
//                    Uri uri = data.getData();
                    String mTempPhotoPath = Environment.getExternalStorageDirectory() + File.separator + "tmp.jpeg";
                    avatarFile = new File(mTempPhotoPath);
                    avatarUri = UriUtil.copy(this, data.getData(), avatarFile);
//                    String  path= ImageUtlis.getRealPathFromUri(this,uri);
//                    String path = GetPathFromUri.getPath(PersonInfoActivity.this, avatarUri);
//                    LogUtil.e("path---",""+path);
                    cropImage(avatarUri);
                }
            } else if (requestCode == REQUEST_CROP_IMAGE) {
//                headImg.setImageURI(avatarUri);
//                uploadAvatar();
//                String path = GetPathFromUri.getPath(PersonInfoActivity.this, avatarUri);
//                LogUtil.e("path---",""+path);
                //将拍摄的照片显示出来
                try {
                    Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(avatarUri));
                    ImageUtlis.saveImg(bitmap,"head.png",this);
                    headImg.setImageBitmap(bitmap);

                String sdcardPath = System.getenv("EXTERNAL_STORAGE");      //获得sd卡路径
                String dir = sdcardPath + "/邻家学苑/head.png";
                    Map<String,String> map = new HashMap<>();

                    map.put("headerurl","png");
                saveHead(Apis.UP_FILE,new File(dir),this);
//                    LoadingDialog.showMassge(PersonInfoActivity.this,"修改中...");
//                    presenter.loadDataGetHeader(map,"",Apis.CHANGE_HEAD,1004,Utlis.getHeadler(PersonInfoActivity.this));

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
//                headImg.setImageURI(avatarUri);
                // TODO 上传图片
            }
        } else {
            // nothing to do here
        }
    }


    private void openCamera() {
        if (hasCamera()) {
            Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            String mTempPhotoPath = Environment.getExternalStorageDirectory() + File.separator + "tmp.jpeg";
            avatarFile = new File(mTempPhotoPath);
            Uri fileUri = FileProvider.getUriForFile(this,
                    this.getApplicationContext().getPackageName() +".file_provider", avatarFile);
            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
            startActivityForResult(captureIntent, REQUEST_TAKE_PHOTO);
        }
    }

    /**
     * 判断系统中是否存在可以启动的相机应用
     *
     * @return 存在返回true，不存在返回false
     */
    public boolean hasCamera() {
        PackageManager packageManager = this.getPackageManager();
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }

    @Override
    public void selectPic(int postion) {

    }

    @Override
    public void returnData(String data, int urlCode) {


        if (TextUtils.isEmpty(data))
        {
            return;
        }
        handler.obtainMessage(urlCode,data).sendToTarget();
    }

    @Override
    public void LoadError(String errorMsg, int urlCode) {
        showToast("请求失败");
        LoadingDialog.hideProgress();
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String str = (String) msg.obj;
            switch (msg.what){
                case 1001:
                    LoadingDialog.hideProgress();
                    if (TextUtils.isEmpty(str)){
                        return;
                    }

                    DataBean bean = Utlis.getDataBean(str);
                    if (bean.getCode()==200){
                        MyApplication.getInstance().userInfo = (UserInfo) JsonUitl.stringToObject(bean.getData(), UserInfo.class);
                        SpUtils.getInstance().save(PersonInfoActivity.this,"userinfo",""+bean.getData());

                        setInfo();
                    }else{
                        showToast(bean.getMessage());
                    }
                    break;
                case 1002:
                    LoadingDialog.hideProgress();
                    bean = Utlis.getDataBean(str);
                    showToast(bean.getMessage());

                    break;
                case 1003:
                    LoadingDialog.hideProgress();
                    bean = Utlis.getDataBean(str);
                    showToast(bean.getMessage());

                    break;
                case 1004:
                    LoadingDialog.hideProgress();
                    bean = Utlis.getDataBean(str);
                    showToast(bean.getMessage());

                    break;
            }

        }
    };

    private void setInfo(){
        if (null!=MyApplication.getInstance().userInfo){
            nickname.setText(""+MyApplication.getInstance().userInfo.getNickname());
            if (MyApplication.getInstance().userInfo.getGender()==0){
                sex.setText("女");
            }else if (MyApplication.getInstance().userInfo.getGender()==1){
                sex.setText("男");
            }else if (MyApplication.getInstance().userInfo.getGender()==3){
                sex.setHint("未设置");
            }

            String cityStr = (String) MyApplication.getInstance().userInfo.getFulladdr();
            if (!TextUtils.isEmpty(cityStr)){
               String a[] =cityStr.split(",");
               if (a.length>0){
                   city.setText(a[a.length-1]);
               }
            }
            Glide.with(this)
                    .load(""+MyApplication.getInstance().userInfo.getHeader())
                    .placeholder(R.mipmap.user_pic)
                    .error(R.mipmap.user_pic)
                    .dontAnimate()
                    .centerCrop()
                    .into(headImg);
//            city.setText(MyApplication.getInstance().userInfo.);
            if (null!=MyApplication.getInstance().userInfo.getBirthday()){
                System.out.println(MyApplication.getInstance().userInfo);
//                long b = Long.parseLong(MyApplication.getInstance().userInfo.getBirthday().toString());
                String sb = Utlis.stampToDate(MyApplication.getInstance().userInfo.getBirthday());
                birthday.setText(sb.substring(0,10)+"");
            }

        }
    }

    /**
     * 上传头像
     */
    public  void saveHead(String url,File file,Context context) {


        OkGo.<String>post(url).headers(Utlis.getHeadler(context))
                .tag(context)
                .params("uploadimg", file)
                .isMultipart(true)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtil.e("返回数据---",""+response.body());
                        DataBean bean = Utlis.getDataBean(response.body());

                        if (bean.getCode()==200){
                            Map<String,String> map = new HashMap<>();

                            map.put("headerurl",bean.getData());
                            presenter.loadDataGetHeader(map,"",Apis.CHANGE_HEAD,1004,Utlis.getHeadler(PersonInfoActivity.this));

                        }else{
                            showToast(bean.getMessage());
                            LoadingDialog.hideProgress();
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        LogUtil.e("上传失败---",""+response.body());
                        showToast("上传失败");
                        LoadingDialog.hideProgress();
                    }
                });
    }
}
